# coding=utf-8
# 单股分析
import os

import pandas as pd
import tushare as ts
from loguru import logger

from models.stock_model import DayInfo2, StockNumber2


def get_name_industry(stock, ana_days):
    df = pd.read_csv('cal_ops/all.csv')
    for row in df.index:
        if stock and df.loc[row]['ts_code'] != stock:
            continue
        sn_obj = StockNumber2(df.loc[row])
        analysis_stock(sn_obj, ana_days)


def analysis_stock(sn_obj, ana_days=100):
    csv_path = f'stocks/{sn_obj.ts_code}.csv'
    if not os.path.exists(csv_path):
        pro = ts.pro_api(token='bbc6f076aa3d2b063cb26376ad12ffd94b53864b42d2344b3aa2039f')
        df2 = pro.daily(ts_code=sn_obj.ts_code)
        save_dir = f'stocks'
        if not os.path.exists(save_dir):
            os.mkdir(save_dir)
        df2.to_csv(csv_path)
        logger.info(f'下载 {sn_obj.link} 成功')

    df2 = pd.read_csv(csv_path)
    if ana_days > len(df2.index):
        logger.error(f'{sn_obj.name} {sn_obj.link} 上市{len(df2.index)}天，小于分析天数{ana_days}')
        return

    over3_arr = []
    under3_arr = []
    for idx, row2 in enumerate(df2.index):
        if idx > ana_days:
            logger.success(f'{sn_obj.name}近{ana_days}日分析完成:')
            logger.success(f'{len(over3_arr)}次涨幅大于3')
            logger.success(f'{len(under3_arr)}次跌幅大于3')
            logger.success('')
            logger.success(sn_obj.link)
            break
        di = DayInfo2(sn_obj.link, sn_obj.name, sn_obj.industry, df2.loc[row2])
        if di.pct_chg >= 3:
            over3_arr.append(di)
        if di.pct_chg <= -3:
            under3_arr.append(di)


def run(stocks, ana_days):
    for s in stocks:
        get_name_industry(s, ana_days)
